﻿using System;
using Microsoft.AspNetCore.Builder;
using Microsoft.Extensions.Configuration;

namespace WebApi.Swagger
{
    public static class SwaggerBuilderExtensions
    {
        public static IApplicationBuilder UseExtensionSwagger(this IApplicationBuilder app, IConfiguration configuration)
        {
            bool isEnableSwagger = Convert.ToBoolean(configuration["Swagger:Enabled"] ?? "false");
            if (isEnableSwagger)
            {
                // 封装集成使用Swagger中间件
                app.UseSwagger(c =>
                {
                    c.RouteTemplate = "doc/{documentName}/swagger.json";
                });

                app.UseSwaggerUI(s =>
                {
                    s.SwaggerEndpoint(
                        $"/doc/{configuration["Swagger:DocName"]}/swagger.json",
                        $"{configuration["Swagger:DocName"]}-{configuration["Swagger:Version"]}");

                    // 是否显示Models
                    var isDisplayModels = Convert.ToBoolean(configuration["Swagger:Models"] ?? "true");
                    if (!isDisplayModels)
                    {
                        s.DefaultModelExpandDepth(-1);
                    }
                });
            }

            return app;
        }

        public static IApplicationBuilder UseGatewaySwagger(this IApplicationBuilder app, IConfiguration configuration)
        {
            bool isEnableSwagger = Convert.ToBoolean(configuration["Swagger:Enabled"]);
            string docNames = configuration["Swagger:ApiServices:DocNames"];
            if (!isEnableSwagger || string.IsNullOrEmpty(docNames))
            {
                return app;
            }

            var apiDocNames = docNames.Trim().Split(',');

            // 为API Gateway封装集成使用Swagger中间件
            app.UseSwagger()
                .UseSwaggerUI(options =>
                {
                    foreach (var apiDocName in apiDocNames)
                    {
                        options.SwaggerEndpoint($"/doc/{apiDocName}/swagger.json", apiDocName);
                    }
                });

            return app;
        }
    }
}
